package com.ls.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.server.domain.DictCategory;
import com.ls.server.domain.DictItem;
import com.ls.server.dto.DictCategoryDTO;
import com.ls.server.dto.DictQueryDTO;
import com.ls.server.mapper.DictCategoryMapper;
import com.ls.server.mapper.DictItemMapper;
import com.ls.server.service.DictCategoryService;
import com.ls.server.vo.DictCategoryVO;
import com.ls.server.vo.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典大类服务实现类
 */
@Service
public class DictCategoryServiceImpl extends ServiceImpl<DictCategoryMapper, DictCategory> implements DictCategoryService {

    private final DictItemMapper dictItemMapper;

    public DictCategoryServiceImpl(DictItemMapper dictItemMapper) {
        this.dictItemMapper = dictItemMapper;
    }

    @Override
    public PageResult<DictCategoryVO> page(DictQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<DictCategory> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(queryDTO.getName())) {
            wrapper.like(DictCategory::getName, queryDTO.getName());
        }
        if (StringUtils.hasText(queryDTO.getCode())) {
            wrapper.like(DictCategory::getCode, queryDTO.getCode());
        }
        wrapper.orderByDesc(DictCategory::getCreateTime);

        // 分页查询
        IPage<DictCategory> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());
        page = baseMapper.selectPage(page, wrapper);

        // 转换为VO
        List<DictCategoryVO> records = page.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 返回分页结果
        return new PageResult<DictCategoryVO>(records, page.getTotal(), queryDTO.getPage(), queryDTO.getSize());
    }

    @Override
    public List<DictCategoryVO> listByVO() {
        // 查询所有字典大类
        List<DictCategory> list = baseMapper.selectList(
                new LambdaQueryWrapper<DictCategory>().orderByAsc(DictCategory::getCode)
        );

        // 转换为VO
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public DictCategoryVO getById(Long id) {
        DictCategory category = baseMapper.selectById(id);
        return category != null ? convertToVO(category) : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(DictCategoryDTO dto) {
        DictCategory category = new DictCategory();
        BeanUtils.copyProperties(dto, category);

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        category.setCreator("admin"); // 实际应从当前登录用户获取
        category.setUpdater("admin"); // 实际应从当前登录用户获取

        return baseMapper.insert(category) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(DictCategoryDTO dto) {
        DictCategory category = baseMapper.selectById(dto.getId());
        if (category == null) {
            return false;
        }

        BeanUtils.copyProperties(dto, category);
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdater("admin"); // 实际应从当前登录用户获取

        return baseMapper.updateById(category) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        // 查询是否存在关联的字典项
        long count = dictItemMapper.selectCount(
                new LambdaQueryWrapper<DictItem>().eq(DictItem::getCategoryId, id)
        );

        if (count > 0) {
            throw new RuntimeException("存在关联的字典项，无法删除");
        }

        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 将实体转换为VO
     * @param category 实体
     * @return VO
     */
    private DictCategoryVO convertToVO(DictCategory category) {
        if (category == null) {
            return null;
        }
        DictCategoryVO vo = new DictCategoryVO();
        BeanUtils.copyProperties(category, vo);
        return vo;
    }
}
